package com.srwl.mytx.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.google.android.material.snackbar.Snackbar;
import com.srwl.mytx.Constant;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Coupon;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.AliService;
import com.srwl.mytx.service.CouponService;
import com.srwl.mytx.activity.MultipleCouponDetailActivity;
import com.srwl.mytx.activity.SingleCouponDetailActivity;
import com.srwl.mytx.utils.ClickUtil;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.redpacketui.ui.base.RPBaseDialogFragment;

import java.math.BigDecimal;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by max on 16/1/22
 */
public class RedPacketDialogFragment extends RPBaseDialogFragment implements View.OnClickListener{

    private String TAG = RedPacketDialogFragment.class.getSimpleName();
    private Coupon coupon;
    private User targetUser;


    private final static String ARGS_RED_PACKET_INFO = "red_packet_info";

    private TextView mTvGreeting;

    private Button mBtnOpen;

    private TextView mTvCheckLucky;

    private TextView mTvTitle;

    private View mAvatarView;



    private OnFragmentInteractionListener mListener;


    public static RedPacketDialogFragment newInstance(Coupon coupon) {
        RedPacketDialogFragment frag = new RedPacketDialogFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARGS_RED_PACKET_INFO, coupon);
        frag.setArguments(args);
        return frag;
    }



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            coupon = getArguments().getParcelable(ARGS_RED_PACKET_INFO);
            targetUser = coupon.getTargetUser();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mAvatarView.getLayoutParams();
        params.setMargins(params.leftMargin, marginTop, params.rightMargin, params.bottomMargin);
    }



    @Override
    protected int getContentViewLayoutID() {
        return R.layout.rp_open_packet_dialog;
    }

    @Override
    protected View getLoadingTargetView(View view) {
        return view.findViewById(R.id.target_layout);
    }

    @Override
    protected void initViewsAndEvents(View view, Bundle savedInstanceState) {
        ImageView ivOpenBg = view.findViewById(R.id.iv_open_bg);
        mBtnOpen = view.findViewById(R.id.btn_open_money);
        View closeLayout = view.findViewById(R.id.layout_closed);
        TextView tvUserName = view.findViewById(R.id.tv_username);
        mTvGreeting = view.findViewById(R.id.tv_greeting);
        mAvatarView = view.findViewById(R.id.layout_avatar);
        ImageView ivAvatar = view.findViewById(R.id.iv_avatar);
        mTvTitle = view.findViewById(R.id.tv_open_title);
        mTvCheckLucky = view.findViewById(R.id.tv_check_lucky);
        mTvCheckLucky.setOnClickListener(this);
        if (targetUser != null) {
           // Glide.with(mContext).load(targetUser.getAvatar()).error(R.drawable.tx_default_avatar).into(ivAvatar);
            GlideLoadUtils.glideLoad(mContext,targetUser.getAvatar(),ivAvatar,R.drawable.tx_default_avatar_1);
            tvUserName.setText(targetUser.getUsername());
        }
        closeLayout.setOnClickListener(this);
        mBtnOpen.setOnClickListener(this);
        Integer status = coupon.getStatus();
        if (coupon.getType() == Constant.COUPON_TYPE_MULTIPLE_AVERAGE || coupon.getType() == Constant.COUPON_TYPE_MULTIPLE_RANDOM) {
            // mTvCheckLucky.setVisibility(View.VISIBLE);
            if (coupon.getType() == Constant.COUPON_TYPE_MULTIPLE_RANDOM) {
                mTvTitle.setText(R.string.title_random_money);
            } else if (coupon.getType() == Constant.COUPON_TYPE_MULTIPLE_AVERAGE) {
                mTvTitle.setText(R.string.send_you_money);
            }
            if (status == Constant.COUPON_STATUS_RECEIVABLE) {//可以领取
                mTvCheckLucky.setVisibility(View.INVISIBLE);
                mBtnOpen.setVisibility(View.VISIBLE);
                mTvGreeting.setText(coupon.getGreeting());
            } else if (status == Constant.COUPON_STATUS_RECEIVED) {//过了
                hadReceive();
            } else if (status == Constant.COUPON_STATUS_EXPIRED) {
                onCouponExpired();
            } else if (status == Constant.COUPON_STATUS_REMAIN_ZERO) {//领完了
                onCouponRemainZero();
            }
        } else if (coupon.getType() == Constant.COUPON_TYPE_SINGLE) {
            mTvCheckLucky.setVisibility(View.INVISIBLE);
            if (status == Constant.COUPON_STATUS_RECEIVABLE) {
                mBtnOpen.setVisibility(View.VISIBLE);
                mTvGreeting.setText(coupon.getGreeting());
            } else if (status == Constant.COUPON_STATUS_EXPIRED) {
                mBtnOpen.setVisibility(View.GONE);
                // tvUserName.setText(targetUser.getTitle());
                mTvTitle.setVisibility(View.INVISIBLE);
                mTvGreeting.setText(R.string.money_expired_str);
            }
        }
    }

    private void onCouponExpired() {
        mTvTitle.setVisibility(View.INVISIBLE);
        mTvGreeting.setText(R.string.money_expired_str);
        mTvCheckLucky.setVisibility(View.INVISIBLE);
        mBtnOpen.setVisibility(View.GONE);
    }

    /**
     * 已经领取
     */
    private void hadReceive() {
        mTvTitle.setVisibility(View.INVISIBLE);
        mTvCheckLucky.setVisibility(View.VISIBLE);
        mTvGreeting.setText("你已经领取了该红包");
        if (coupon.getType() == Constant.COUPON_TYPE_MULTIPLE_AVERAGE) {
            mTvCheckLucky.setText("看看领取详情");
        }
        mBtnOpen.setVisibility(View.GONE);
    }

    private void onCouponRemainZero() {
        mTvTitle.setVisibility(View.INVISIBLE);
        mTvCheckLucky.setVisibility(View.VISIBLE);
        mTvGreeting.setText(R.string.money_is_out);
        if (coupon.getType() == Constant.COUPON_TYPE_MULTIPLE_AVERAGE) {
            mTvCheckLucky.setText("看看领取详情");
            // mTvGreeting.setText(R.string.money_is_out_avg);
        }
        mBtnOpen.setVisibility(View.GONE);
    }

    @Override
    public void onClick(View v) {
        if (ClickUtil.isFastClick()) return;
        switch (v.getId()) {
            case R.id.btn_open_money:

                showLoading();
                mBtnOpen.setClickable(false);

              /*  JSONObject body = new JSONObject();
                body.put("token", Helper.getInstance().getUserToken());
                body.put("ct", coupon);
*/
                if (coupon.getType() == Constant.COUPON_TYPE_ALI_FUND) {
                    /* receiveFundCoupon(body);*/
                } else if (coupon.getType() == Constant.COUPON_TYPE_SINGLE) {
                    receiveCoinCoupon(coupon);
                } else if (coupon.getType() == Constant.COUPON_TYPE_MULTIPLE_AVERAGE || coupon.getType() == Constant.COUPON_TYPE_MULTIPLE_RANDOM) {

                    receivedMultipleCoupon();

                }


                break;
            case R.id.layout_closed:
                dismiss();
                break;
            case R.id.tv_check_lucky:
                //查看详情
                Intent intent = new Intent(getActivity(), MultipleCouponDetailActivity.class);
                intent.putExtra(Constant.EXTRA_INFO_COUPON, coupon);
                startActivity(intent);
                this.dismissAllowingStateLoss();
                break;
        }
    }

    /**
     * 接收一对多金币红包
     *
     * @param
     */
    private void receivedMultipleCoupon() {
        RetrofitManager.getInstance().createRequest(CouponService.class)
                .receiveMultipleCoupon(coupon)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        hideLoading();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "接收一对多红包出错：" + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "接收一对多红包出错：" + result.getMsg());
                            switch (result.getStatus()) {
                                case Constant.GET_LOCK_FAIL:
                                    showToast(mBtnOpen, getString(R.string.system_busy));
                                    break;
                                case Constant.FUND_COUPON_STATUS_EXPIRED:
                                    //  showToast(mBtnOpen, getString(R.string.red_packet_expire));
                                    coupon.setStatus(Constant.COUPON_STATUS_EXPIRED);
                                    if (mListener != null) {
                                        mListener.onCouponExpire(coupon);
                                    }
                                    onCouponExpired();
                                    if (mListener != null) {
                                        mListener.onStatusChange(Constant.COUPON_STATUS_EXPIRED);
                                    }
                                    break;
                                case Constant.RECEIVE_COUPON_ERROR_RECEIVED:
                                    //  showToast(mBtnOpen, getString(R.string.red_packet_already_received));
                                    // mBtnOpen.setVisibility(View.INVISIBLE);
                                    hadReceive();
                                    if (mListener != null) {
                                        mListener.onStatusChange(Constant.COUPON_STATUS_RECEIVED);
                                    }
                                    break;

                                case Constant.RECEIVE_COUPON_ERROR_REMAIN_ZERO:
                                    //showToast(mBtnOpen, getString(R.string.money_is_out));
                                    onCouponRemainZero();
                                    if (mListener != null) {
                                        mListener.onStatusChange(Constant.COUPON_STATUS_REMAIN_ZERO);
                                    }
                                    break;
                                default:
                                    showToast(mBtnOpen, getString(R.string.system_busy));
                            }
                            return;
                        }
                        Log.d(TAG, "接收一对多红包完成");

                        //更新本地余额
                        JSONObject jsonObject = (JSONObject) result.getData();
                        Double balance = jsonObject.getDouble("balance");
                        Coupon childCoupon = jsonObject.getObject("childCoupon", Coupon.class);
                        Boolean isEmpty = jsonObject.getBoolean("isEmpty");


                        UserProfileManager.getInstance().setUserBalance(balance);
                        //此红包已经领取,把领取的子红包 返回
                        childCoupon.setTargetUser(coupon.getTargetUser());
                        if (mListener != null) {
                            mListener.onReceiveCouponComplete(childCoupon, isEmpty);
                        }
                        //接收成功，进入红包详情
                        Intent intent = new Intent(getContext(), MultipleCouponDetailActivity.class);
                        intent.putExtra(Constant.EXTRA_INFO_COUPON, coupon).putExtra(Constant.EXTRA_INFO_CHILD_COUPON, childCoupon);
                        startActivity(intent);
                        dismiss();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        hideLoading();
                        Log.e(TAG, "接收一对多红包出错：" + t.getMessage());

                    }
                });

    }

    /**
     * 接收蚂蚁金币红包
     *
     * @param coupon
     */
    private void receiveCoinCoupon(Coupon coupon) {
        RetrofitManager.getInstance().createRequest(CouponService.class)
                .receiveSingleCoupon(coupon)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        hideLoading();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "接收一对一红包出错：" + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "接收一对一红包出错：" + result.getMsg());
                            switch (result.getStatus()) {
                                case Constant.TOKEN_INVALID:
                                    showToast(getString(R.string.system_busy));
                                    return;
                                case Constant.FUND_COUPON_STATUS_EXPIRED:
                                    //  showToast(getString(R.string.red_packet_expire));
                                    coupon.setStatus(Constant.COUPON_STATUS_EXPIRED);
                                    if (mListener != null) {
                                        mListener.onCouponExpire(coupon);
                                    }
                                    onCouponExpired();
                                    return;
                                case Constant.FUND_COUPON_TARGET_USER_MISMATCHING:
                                    showToast(getString(R.string.fund_coupon_target_user_mismatching));
                                    return;
                            }
                        }
                        Log.d(TAG, "接收一对一红包完成");
                        //更新本地余额
                        BigDecimal totalBalaence = (BigDecimal) result.getData();
                        if (totalBalaence == null) {
                            return;
                        }
                        UserProfileManager.getInstance().setUserBalance(totalBalaence.doubleValue());
                        coupon.setStatus(Constant.COUPON_STATUS_RECEIVED);

                        //通过结果，通知该红包已经领取，发个回执告诉接收方，此红包已经领取
                        if (mListener != null) {
                            mListener.onReceiveCouponComplete(coupon, false);
                        }
                        //接收成功，进入红包详情
                        startActivity(new Intent(getContext(), SingleCouponDetailActivity.class).putExtra(Constant.EXTRA_INFO_COUPON, coupon));
                        dismiss();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        hideLoading();
                        Log.e(TAG, "接收一对一红包出错：" + t.getMessage());

                    }
                });
    }

    /**
     * 接收支付宝现金红包
     *
     * @param body
     */
    private void receiveFundCoupon(JSONObject body) {
        RetrofitManager.getInstance().createRequest(AliService.class)
                .receiveFundCoupon(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });
    }


    private void showToast(View view, String msg) {

        Snackbar.make(view, msg, Snackbar.LENGTH_LONG).show();

    }




    public void setOnFragmentInteractionListener(OnFragmentInteractionListener mListener) {
        this.mListener = mListener;
    }

    public interface OnFragmentInteractionListener {
        //当红包接收完成 返回状态判断是否领取完
        void onReceiveCouponComplete(Coupon coupon, boolean isEmpty);


        void onStatusChange(Integer status);

        //当红包过期
        void onCouponExpire(Coupon coupon);

    }


}
